package com.sxf.controller.blog.admin;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.ModelAndView;

import com.sxf.common.tools.WPConstants;
import com.sxf.controller.SuperController;
import com.sxf.controller.formbean.LinkVO;
import com.sxf.controller.formbean.TermVO;
import com.sxf.domain.Link;
import com.sxf.domain.TermRelationships;
import com.sxf.domain.User;
import com.sxf.formbean.LinkForm;
import com.sxf.mybatis.page.Pagination;
import com.sxf.querybean.LinkQuery;
import com.sxf.querybean.TermQuery;
import com.sxf.querybean.TermRelationshipsQuery;
import com.sxf.service.LinkService;
import com.sxf.service.TermRelationshipsService;
import com.sxf.service.TermService;
import com.sxf.service.TermTaxonomyService;
import com.sxf.view.datatables.DataTables;
import com.sxf.view.datatables.DatatablesHelp;

/**
 * @author phsxf01
 */
@Controller
@RequestMapping("blog/admin/link")
public class LinkController extends SuperController {
	@Resource
	private LinkService linkService;
	@Resource
	private TermService termService;
	@Resource
	private TermRelationshipsService termRelationshipsService;
	@Resource
	private TermTaxonomyService termTaxonomyService;

	@RequestMapping("")
	public ModelAndView toLink() throws Exception {
		ModelAndView mav = new ModelAndView();
		TermQuery query = new TermQuery();
		query.setTaxonomy(WPConstants.TAXONOMY_LINKA_CATEGORY);
		List<TermVO> termList = termService.queryList(query);
		mav.addObject("termList", termList);
		return mav;
	}

	@RequestMapping("/listAjax")
	@ResponseBody
	public Pagination<LinkVO> listAjax(
			@RequestParam(value = "page", required = false) String page,
			@RequestParam(value = "rows", required = false) String rows,
			HttpServletRequest request) throws Exception {
		LinkQuery query = new LinkQuery();
		if (StringUtils.hasText(page)) {
			try {
				query.setCurrentPage(Integer.parseInt(page));
			} catch (Exception e) {
			}
		}
		if (StringUtils.hasText(rows)) {
			try {
				query.setPageSize(Integer.parseInt(rows));
			} catch (Exception e) {
			}
		}
		String dtjson = request.getParameter("dtjson");
		if (StringUtils.hasText(dtjson)) {
			DataTables dt = DatatablesHelp.getDataTable(dtjson);
			String name = dt.getSearch();
			if (StringUtils.hasText(name)) {
				query.setName(name);
			}
		}

		String linkCategory = request.getParameter("linkCategory");
		if (StringUtils.hasText(linkCategory)) {
			query.setTermId(Long.valueOf(linkCategory));
		}
		Pagination<LinkVO> linkPage = linkService.queryPage(query);
		return linkPage;
	}

	@RequestMapping("/toAddOrUpdate")
	public ModelAndView toAddOrUpdate(
			@RequestParam(value = "linkId", required = false) Long linkId)
			throws Exception {
		ModelAndView mav = new ModelAndView();
		mav.setViewName("/blog/admin/link_edit");
		if (linkId != null) {
			LinkQuery query = new LinkQuery();
			query.setId(linkId);
			LinkVO link = linkService.queryOne(query);
			mav.addObject("link", link);
		}
		return mav;
	}

	@RequestMapping("/doAddOrUpdate")
	public ModelAndView doAddOrUpdate(@Valid @ModelAttribute LinkForm form,
			WebRequest request) throws Exception {
		ModelAndView mav = new ModelAndView();
		if (form != null) {
			int i = 0;
			Link link = new Link();
			BeanUtils.copyProperties(form, link);
			mav.setViewName("redirect:/blog/admin/link");
			if (form.getId() != null) {
				// 更新
				link.setUpdated(new Date());
				if (link.getVisible() == null) {
					link.setVisible("Y");
				}
				i = linkService.update(link);
			} else {
				// 插入
				if (link.getVisible() == null) {
					link.setVisible("Y");
				}
				User user = getCurrentUser();
				link.setOwner(user.getId());
				i = linkService.insert(link);
			}
			if (i > 0) {
				Long linkId = link.getId();
				// 删除原来link对应的分类和标签
				deleteTermByLinkId(linkId);
				// 处理分类
				String[] categoryArr = request
						.getParameterValues("link_category[]");
				if (categoryArr != null) {
					for (String category : categoryArr) {
						TermRelationshipsQuery trsq = new TermRelationshipsQuery();
						trsq.setObjectId(linkId);
						trsq.setTermTaxonomyId(Long.valueOf(category));
						if (termRelationshipsService.queryOne(trsq) == null) {
							TermRelationships trs = new TermRelationships();
							trs.setObjectId(linkId);
							trs.setTermTaxonomyId(Long.valueOf(category));
							trs.setTermOrder(0);
							termRelationshipsService.insert(trs);
						}
					}
				}
				if (form.getId() == null) {
					mav.setViewName("redirect:/blog/admin/link/toAddOrUpdate?linkId="
							+ link.getId());
				}
			}
		}

		return mav;
	}

	@RequestMapping("/delete")
	@ResponseBody
	public String delete(@RequestParam(required = true) Long linkId,
			WebRequest request) throws Exception {
		if (linkId != null) {
			Link link = new Link();
			link.setId(linkId);
			linkService.delete(link);
			// 删除原来link对应的分类和标签
			deleteTermByLinkId(linkId);
		}
		return "success";
	}

	private boolean deleteTermByLinkId(Long linkId) {
		boolean flag = true;
		TermQuery termQuery = new TermQuery();
		List<String> taxonomyList = new ArrayList<String>();
		taxonomyList.add(WPConstants.TAXONOMY_LINKA_CATEGORY);
		termQuery.setTaxonomyList(taxonomyList);
		List<TermVO> termVOList = termService.queryList(termQuery);
		if (termVOList != null && !termVOList.isEmpty()) {
			TermRelationships trs = new TermRelationships();
			trs.setObjectId(linkId);
			for (TermVO tv : termVOList) {
				trs.setTermTaxonomyId(tv.getTaxonomyId());
				termRelationshipsService.delete(trs);
			}
		}
		return flag;
	}
}
